<template>
  <el-dialog title="新增" v-model="visible" :close-on-click-modal="false" draggable>
    <el-form ref="coreDialogFormRef" :model="coreForm" :rules="dataRules" label-width="120px" v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="24" class="mb20">
          <el-form-item label="预约时间" prop="choiceDate" >
            <el-date-picker type="datetime" placeholder="选择日期时间" value-format="YYYY-MM-DD HH:mm"
                format="YYYY-MM-DD HH:mm" style="width: 100%" v-model="coreForm.choiceDate" />
          </el-form-item>
        </el-col>
        <!--
      <el-col :span="12" class="mb20">
        <el-form-item label="日期" prop="infusionDate" >
          <el-date-picker v-model="coreForm.infusionDate" type="date" placeholder="选择日期"
              format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 100%"/>
        </el-form-item>
      </el-col>
      <el-col :span="12" class="mb20">
        <el-form-item label="预约时间" prop="yjkssj" >
          <el-time-select placeholder="选择时间" v-model="coreForm.yjkssj"
              start="08:00" step="00:15" end="16:00" />
        </el-form-item>
      </el-col>
      -->
      <el-col :span="12" class="mb20">
      <el-form-item label="居民姓名" prop="name">
        <el-input v-model="coreForm.name" clearable placeholder="请输入居民姓名" />
      </el-form-item>
      </el-col>
      <el-col :span="12" class="mb20">
      <el-form-item label="身份证号" prop="certNo">
        <el-input v-model="coreForm.certNo" clearable placeholder="请输入身份证号" />
      </el-form-item>
      </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="皮条系数" prop="ptxs">
            <el-input v-model="coreForm.ptxs" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="滴速" prop="ds">
            <el-input v-model="coreForm.ds" clearable />
          </el-form-item>
        </el-col>
      <el-col :span="12" class="mb20">
        <el-form-item label="输液A" prop="syal">
          <el-input v-model="coreForm.syal" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="12" class="mb20">
        <el-form-item label="输液B" prop="sybl">
          <el-input v-model="coreForm.sybl" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="12" class="mb20">
        <el-form-item label="输液C" prop="sycl">
          <el-input v-model="coreForm.sycl" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="12" class="mb20">
        <el-form-item label="输液D" prop="sydl">
          <el-input v-model="coreForm.sydl" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="12" class="mb20">
        <el-form-item label="输液E" prop="syel">
          <el-input v-model="coreForm.syel" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="12" class="mb20">
        <el-form-item label="输液F" prop="syfl">
          <el-input v-model="coreForm.syfl" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="12" class="mb20">
        <el-form-item label="特殊输液A量" prop="tssyal">
          <el-input v-model="coreForm.tssyal" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="12" class="mb20">
        <el-form-item label="特殊输液A滴速" prop="tssyads">
          <el-input v-model="coreForm.tssyads" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="12" class="mb20">
        <el-form-item label="特殊输液B量" prop="tssybl">
          <el-input v-model="coreForm.tssybl" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="12" class="mb20">
        <el-form-item label="特殊输液B滴速" prop="tssybds">
          <el-input v-model="coreForm.tssybds" clearable />
        </el-form-item>
      </el-col>
      </el-row>
    </el-form>
    <template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="loading">{{ $t('common.confirmButtonText') }}</el-button>
			</span>
    </template>
    <iframe id="printFrame" style="display:none;" src="/print/AppointmentPrint.html"  />
  </el-dialog>
</template>

<script setup lang="ts" name="CoreDialogFromDialog">
import { useI18n } from 'vue-i18n';
import { putCoreObj, getInfusionCore, checkInfusionSeatNum, InfusionCoreProps } from '/@/api/infusion/config';
import { useMessage } from '/@/hooks/message';
import { ElMessageBox } from 'element-plus';
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const { t } = useI18n();

// 定义变量内容
const visible = ref(false);
const loading = ref(false);
const coreDialogFormRef = ref();

// 定义需要的数据
const coreForm = reactive<InfusionCoreProps>({
  choiceDate: '' ,
  infusionDate: '' ,
  name: '',
  certNo: '',
  syal: '',
  sybl: '',
  sycl: '',
  sydl: '',
  syel: '',
  syfl: '',
  tssyal: '',
  tssyads: '',
  tssybl: '',
  tssybds: '',
  ptxs: '20',
  ds: '60',
  yjkssj: '',
  sjkssj: '',
  yjjssj: '',
  sjjssj: '',
});

// 表单校验规则
const dataRules = reactive({
  name: [{required: true, message: '居民姓名不能为空', trigger: 'blur'}],
  choiceDate: [{ type: 'date', required: true, message: '请选择预约日期', trigger: 'change' }],
  syal: [{required: true, message: '输液A不能为空', trigger: 'blur'}],
});

// 打开弹窗
const openDialog = async (type:string,coreId:string) => {
  visible.value = true;
  console.log('type：【' + type + '】，coreId：【' + coreId + '】');
  const params = {
    coreId : coreId
  }
  let coreData:InfusionCoreProps = { };
  if (type !== 'add') {
    let data = await getInfusionCore(params);
    coreData = data.data;
  }
  // 重置表单数据
  nextTick(() => {
    coreDialogFormRef.value?.resetFields();
    if (coreId) {
      coreForm['coreId'] = coreData['coreId'];
      coreForm['seatId'] = coreData['seatId'];
      coreForm['yjkssj'] = coreData['yjkssj'];
      if (type === 'next') {
        coreForm['coreId'] = undefined;
        coreForm['seatId'] = undefined;
        coreForm['yjkssj'] = undefined;
      } else {
        coreForm['choiceDate'] = coreData['infusionDate'] + ' ' + coreData['yjkssj']
      }
      coreForm['infusionDate'] = coreData['infusionDate'];
      coreForm['name'] = coreData['name'];
      coreForm['certNo'] = coreData['certNo'];
      coreForm['syal'] = coreData['syal'];
      coreForm['sybl'] = coreData['sybl'];
      coreForm['sycl'] = coreData['sycl'];
      coreForm['sydl'] = coreData['sydl'];
      coreForm['syel'] = coreData['syel'];
      coreForm['syfl'] = coreData['syfl'];
      coreForm['tssyal'] = coreData['tssyal'];
      coreForm['tssyads'] = coreData['tssyads'];
      coreForm['tssybl'] = coreData['tssybl'];
      coreForm['tssybds'] = coreData['tssybds'];
      coreForm['totalInfusion'] = coreData['totalInfusion'];
      coreForm['ptxs'] = coreData['ptxs'];
      coreForm['ds'] = coreData['ds'];
      coreForm['syyjsc'] = undefined;
      coreForm['yjjssj'] = undefined;
      coreForm['sjkssj'] = undefined;
      coreForm['sjjssj'] = undefined;
    } else {
      coreForm['choiceDate'] = undefined;
      coreForm['coreId'] = undefined;
      coreForm['seatId'] = undefined;
      coreForm['infusionDate'] = undefined;
      coreForm['name'] = undefined;
      coreForm['certNo'] = undefined;
      coreForm['syal'] = undefined;
      coreForm['sybl'] = undefined;
      coreForm['sycl'] = undefined;
      coreForm['sydl'] = undefined;
      coreForm['syel'] = undefined;
      coreForm['syfl'] = undefined;
      coreForm['tssyal'] = undefined;
      coreForm['tssyads'] = undefined;
      coreForm['tssybl'] = undefined;
      coreForm['tssybds'] = undefined;
      coreForm['totalInfusion'] = undefined;
      coreForm['ptxs'] = '20';
      coreForm['ds'] = '60';
      coreForm['yjkssj'] = undefined;
      coreForm['sjkssj'] = undefined;
      coreForm['syyjsc'] = undefined;
      coreForm['yjjssj'] = undefined;
      coreForm['sjjssj'] = undefined;
    }
  });
};

// 保存数据
const onSubmit = async () => {
  const valid = await coreDialogFormRef.value.validate().catch(() => {});
  if (!valid) return false;
  let dateTime = coreForm.choiceDate?.split(' ');
  if (dateTime && dateTime.length > 1 ) {
    coreForm['infusionDate'] = dateTime[0];
    coreForm['yjkssj'] = dateTime[1];
  }
  loading.value = true;
  try {
    const number = await checkInfusionSeatNum(coreForm);
    if (number.data >= 10) {
      nextConfirm(number.data);
    } else {
      await saveCoreData();
    }
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};

const saveCoreData = async () => {
  let msg = coreForm.coreId === undefined ? '添加成功！' : '修改成功！'
  const data = await putCoreObj(coreForm);
  useMessage().success(msg);
  await printAppointment(data.data);
}

const nextConfirm = (number:number) => {
  ElMessageBox({
    closeOnClickModal: false,
    closeOnPressEscape: false,
    title: t('user.logOutTitle'),
    message: '当前时间段已有【' + number + '】人，是否继续添加！',
    showCancelButton: true,
    confirmButtonText: t('user.logOutConfirm'),
    cancelButtonText: t('user.logOutCancel'),
    buttonSize: 'default',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        // 进行保存
        saveCoreData();
      }
      // 关闭弹窗
      done();
    }
  }).catch(() => {});
}

const printAppointment = (data:{name:string,infusionDate:string,yjkssj:string,yjjssj:string}) => {
  const postData = {
    data: {
      name: data['name'],
      infusionDate: data['infusionDate'],
      yjkssj: data['yjkssj'],
      yjjssj: data['yjjssj'],
    }
  };
  const iframe = document.getElementById('printFrame');
  iframe.contentWindow.postMessage(postData, '*');
};

// 暴露变量 只有暴漏出来的变量 父组件才能使用
defineExpose({
  openDialog,
});
</script>
